import { add, queryByPage } from '../../utils/db';
import { uploadImage } from '../../utils/uploadImage'
Page({
  data: {
    pageEnd: false,
    currPage: 0,
    isUploaderHide: true,
    title: '',
    desc: '',
    url: '',
    allAlbums: [],
  },
  onLoad: function () {
    this.getAlbumsByPage(this.data.currPage)
  },
  doUpload: function () {
    // 选择图片
    const filename = 'albums/album' + Date.now()
    uploadImage(this, filename).then(res => {
      this.setData({ url: res.fileID, })
    })
  },
  formSubmit(e) {
    const value = e.detail.value
    const album = {
      url: this.data.url,
      likes: [],
      favorites: [],
      comments: [],
      created: Date.now(),
      updated: Date.now(),
      ...value,
    }
    if (!this.data.url) {
      wx.showToast({ icon: 'none', title: '请上传图片' })
      return
    }
    this.addAlbum(album)
  },
  addAlbum(album) {
    add('albums', album).then(res => {
      wx.showToast({ icon: 'success', title: '上传成功' })
      this.cleanForm()
      this.refreshAlbum()
      this.setData({ isUploaderHide: true, })
    })
  },
  cleanForm() {
    this.setData({ desc: '', title: '', url: '', })
  },
  getAlbumsByPage(page) {
    const LIMIT =20 
    if (this.data.pageEnd) { return }
    queryByPage('albums', {}, page, LIMIT).then(res => {
      if (res.length < LIMIT) { this.setData({ pageEnd: true }) }
      const oldCount = this.data.allAlbums.length
      res.forEach((album, index) => {
        this.setData({
          [`allAlbums[${oldCount + index }]`]: album,
        })
      })
    })
  },
  showUploader() {
    this.setData({ isUploaderHide: false, })
  },
  hideUploader() {
    this.setData({ isUploaderHide: true, })
  },
  refreshAlbum() {
    this.setData({
      allAlbums: [],
      currPage: 0,
      pageEnd: false,
    })
    this.getAlbumsByPage(0)
  },
  goDetail(e) {
    const currAlbum = this.data.allAlbums[e.detail]
    const {_opneid, _id} = currAlbum
    const params = `openid=${_opneid}&id=${_id}`
    wx.navigateTo({
      url: `/pages/albumDetail/albumDetail?${params}`
    })
  },
  onPullDownRefresh: function () {
    this.refreshAlbum()
    wx.stopPullDownRefresh()
  },

  onReachBottom: function () {
    this.setData({ currPage: this.data.currPage + 1 })
    this.getAlbumsByPage(this.data.currPage)
  },

  onShareAppMessage: function () {

  }
})